package com.neusoft.hifly.dictionary.area.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.StringConstants;
import com.neusoft.hifly.core.basic.service.impl.CTSaaSBaseServiceImpl;
import com.neusoft.hifly.core.log.annotation.LogType;
import com.neusoft.hifly.core.log.annotation.OperationLog;
import com.neusoft.hifly.core.utils.GlobalConstants;
import com.neusoft.hifly.dictionary.area.dao.IAreaDao;
import com.neusoft.hifly.dictionary.area.entity.AreaObj;
import com.neusoft.hifly.dictionary.area.service.IAreaService;
import com.neusoft.hifly.dynamicds.multi.annotation.MultiDynamicRoutingDataSource;

/**
 * Title: 数据字典服务
 * <p>
 * Description: 区信息 Service
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service
@MultiDynamicRoutingDataSource
public class AreaServiceImpl extends CTSaaSBaseServiceImpl implements IAreaService {
	@Autowired(required = false)
	private IAreaDao areaDao;

	/**
	 * 保存对象
	 *
	 * @param obj
	 *            对象
	 * @throws SystemErrorException
	 *             自定义异常
	 */
	@Override
	@CacheEvict(value = "dic:area", allEntries = true)
	@OperationLog(method = LogType.UPDATE, msg = "区信息")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void saveOrUpdate(final AreaObj obj) throws SystemErrorException {
		if (obj == null) {
			return;
		}

		final AreaObj oldObj = areaDao.getByLogicId(obj.getLogicId());

		// 有ID的话要判断是否保存还是更新
		if (oldObj == null) {
			// 保存

			obj.setId(idWorker.nextId());

			if (obj.getLogicId() == GlobalConstants.ABS_ID) {
				obj.setLogicId(idWorker.nextId());
			}

			this.setForm(obj, obj);

			areaDao.insert(obj);

		} else {
			// 更新

			this.setForm(obj, oldObj);

			areaDao.updateById(oldObj);

		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param logicId
	 *            对象ID
	 */
	@Override
	@CacheEvict(value = "dic:area", allEntries = true)
	@OperationLog(method = LogType.DELETE, msg = "区信息")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByLogicId(final long logicId) {
		areaDao.deleteByLogicId(logicId);
	}

	/**
	 * 批量删除对象
	 *
	 * @param logicIds
	 *            对象ID，多id使用英文逗号分隔
	 */
	@Override
	public void deleteByBatch(final String logicIds) {
		if (StringUtils.isEmpty(logicIds)) {
			return;
		}
		final String[] logicIdArr = logicIds.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (logicIdArr == null) {
			return;
		}
		for (final String logicId : logicIdArr) {
			if (StringUtils.isEmpty(logicId)) {
				continue;
			}
			this.deleteByLogicId(Long.parseLong(logicId));
		}
	}

	/**
	 * 根据id查询对象
	 *
	 * @param logicId
	 *            对象logicId
	 * @return 对象
	 */
	@Override
	public AreaObj getByLogicId(final long logicId) {
		return areaDao.getByLogicId(logicId);
	}

	/**
	 * 查询所有对象
	 *
	 * @return 对象集合
	 */
	@Override
	public List<AreaObj> findAll() {
		return areaDao.findAll();
	}

	/**
	 * 通过城市ID查询地区
	 *
	 * @param cityLogicId
	 *            城市ID
	 * @return 对象集合
	 */
	@Override
	@Cacheable(value = "dic:area")
	public List<AreaObj> findByCityLogicId(final long cityLogicId) {
		return areaDao.findByCityLogicId(cityLogicId);
	}

	/**
	 * 根据条件查询
	 *
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 集合
	 */
	@Override
	public List<AreaObj> search(final Map<String, Object> property) {
		final QueryWrapper<AreaObj> queryWrapper = new QueryWrapper<AreaObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, true, new String[] { "AREA_ORDER", "UPDATE_TIME" });
		return areaDao.selectList(queryWrapper);
	}

	/**
	 * 根据条件查询
	 *
	 * @param offset
	 *            当前页数
	 * @param limit
	 *            分页长度
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 返回Map
	 */
	@Override
	public IPage<AreaObj> search(final int offset, final int limit, final Map<String, Object> property) {
		final IPage<AreaObj> page = new Page<AreaObj>(offset, limit);
		final QueryWrapper<AreaObj> queryWrapper = new QueryWrapper<AreaObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, true, new String[] { "AREA_ORDER", "UPDATE_TIME" });
		return areaDao.selectPage(page, queryWrapper);
	}

	/**
	 * 复制信息
	 *
	 * @param fromObj
	 *            原信息
	 * @param toObj
	 *            新信息
	 */
	private void setForm(final AreaObj fromObj, final AreaObj toObj) {
		toObj.setCityLogicId(fromObj.getCityLogicId());
		toObj.setName(StringUtils.trimToEmpty(fromObj.getName()));
		toObj.setMyOrder(fromObj.getMyOrder());

	}

	/**
	 * 将对象属性替换成数据库列
	 *
	 * @param property
	 *            参数
	 */
	private void replaceProperty(final Map<String, Object> property) {
		if (property != null) {
			if (property.containsKey("cityLogicId")) {
				property.put("CITY_LOGIC_ID", property.get("cityLogicId"));
				property.remove("cityLogicId");
			}
			if (property.containsKey("name")) {
				property.put("AREA_NAME", property.get("name"));
				property.remove("name");
			}
			if (property.containsKey("myOrder")) {
				property.put("AREA_ORDER", property.get("myOrder"));
				property.remove("myOrder");
			}
			if (property.containsKey("updatePerson")) {
				property.put("UPDATE_PERSON", property.get("updatePerson"));
				property.remove("updatePerson");
			}
			if (property.containsKey("updateTime")) {
				property.put("UPDATE_TIME", property.get("updateTime"));
				property.remove("updateTime");
			}

		}
	}
}